package com.sherlocky.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PropertiesUtil {
	private static Map<String, Map<String,Object>> GLOBAL_MAP = new HashMap<String, Map<String,Object>>();
	private static Log logger = LogFactory.getLog(PropertiesUtil.class);
	private static final String DATELINE = "dateline";
	
	public static String getValue(String res, String key) {
		return getValue(res, key, "");
	}
	
	public static String getValue(String res, String key, String defaultValue) {
		//File f = new File(PropertiesUtil.class.getClassLoader().getResource(res).getFile());
		// 用url方式代替直接getFile，避免路径中空格引起的找不到文件问题
		URL url = PropertiesUtil.class.getClassLoader().getResource(res);
		File f = null;
		try {
			f = new File(url.toURI());
		} catch (URISyntaxException e1) {
			logger.error("读取" + url + "出错", e1);
			return defaultValue;
		}
		if (GLOBAL_MAP.get(res) != null && (Long) GLOBAL_MAP.get(res).get(DATELINE) == f.lastModified() && GLOBAL_MAP.get(res).get(key) != null) {
			return (String) GLOBAL_MAP.get(res).get(key);
		}
		
		Properties p = new Properties();
		try {
			p.load(new FileInputStream(f));
			String value = p.getProperty(key);
			Map<String, Object> map = GLOBAL_MAP.get(res);
			if (map == null) {
				map = new HashMap<String, Object>();
			}
			map.put(key, value);
			map.put(DATELINE, f.lastModified());
			GLOBAL_MAP.put(res, map);
			return value;
		} catch (IOException e) {
			logger.error("[Properties]无法获取'" + res + "'文件中的'" + key + "'值", e);
		}
		return defaultValue;
	}
}
